我的Bilibili频道:香芋派Taro
我的个人博客:taropie0224.github.io(阅读体验更佳)
我的公众号:香芋派的烘焙坊
我的音频技术交流群:1136403177
我的个人微信:JazzyTaroPie

https://leetcode-cn.com/problems/max-area-of-island/

题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution
{
int getArea(vector<vector<int> > &grid, int i, int j)
{
//由于坐标每次 +1 ,所以判断是否等于数组长度即可
if (i == grid.size() || i < 0)
return 0;
else if (j == grid[0].size() || j < 0)
return 0;
if (grid[i][j] == 1)
{
grid[i][j] = 0;
return 1 + getArea(grid, i + 1, j) + getArea(grid, i - 1, j) + getArea(grid, i, j + 1) + getArea(grid, i, j - 1);
}
return 0;
}

public:
int maxAreaOfIsland(vector<vector<int> > &grid)
{
int maxArea = 0;
int area = 0;
for (int i = 0; i < grid.size(); i++)
{
for (int j = 0; j < grid[0].size(); j++)
{
if (grid[i][j] == 1)
{
//以此为中心,向四周扩散
area = getArea(grid, i, j);
maxArea = maxArea > area ? maxArea : area;
}
}
}
return maxArea;
}
};